<template>
    <div class="fourth-content">
        <div class="fourth-left">
            <div class="search-line">
                职级：
                <el-input v-model="keyword" class="w-200" size="small"></el-input>
                <el-button @click="filterList" size="small" type="success">查询</el-button>
            </div>
            <el-table :data="tableData"
                      @row-click="clickRow"
                      highlight-current-row
                      style="width: 500px"
                      border
            >
                <el-table-column type="index" prop="type" label="序号" width="50" align="center"></el-table-column>
                <el-table-column label="业务线" prop="businessName" align="center" width="120"></el-table-column>
                <el-table-column label="部门名称" prop="departmentName" align="center" width="120"></el-table-column>
                <el-table-column label="职级" prop="rankName" align="center" width="115"></el-table-column>
                <el-table-column label="绝对值" prop="rankMagnitude" align="center" width="94">
                    <template slot-scope="scope">{{scope.row.rankMagnitude}}%</template>
                </el-table-column>
            </el-table>
            <el-pagination
                    layout="total, sizes, prev, pager, next"
                    style="margin-top:30px"
                    :current-page.sync="tableConfig.pageNum"
                    :page-sizes="[10, 20, 30, 40]"
                    :page-size="tableConfig.pageSize"
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                    :total="tableConfig.totalSize">
            </el-pagination>
        </div>
        <div class="fourth-right">
            <div class="search-line">
                <el-button size="mini" @click="addChild" type="primary">新增</el-button>
            </div>
            <el-table :data="personSettingMap[currentRow.id]" border>
                <el-table-column label="序号" type="index" align="center"></el-table-column>
                <el-table-column label="员工名称" prop="staffName" align="center"></el-table-column>
                <el-table-column label="工号" prop="staffCode" align="center"></el-table-column>
                <el-table-column label="绝对值" prop="absolute" align="center">
                    <template slot-scope="scope">{{scope.row.absolute}}%</template>
                </el-table-column>
                <el-table-column label="操作" align="center" width="100">
                    <template slot-scope="scope">
                        <el-button type="text" @click="handleStaff('edit', scope.$index, scope.row)">编辑</el-button>
                        <el-button type="text" @click="handleStaff('del', scope.$index, scope.row)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <el-dialog :title="handleStaffIndex < 0  ? '新增' : '编辑'" :visible.sync="dialogVisible" width="500px">
                <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="120px" class="demo-ruleForm">
                    <el-form-item label="业务线：">
                        {{currentRow ? currentRow.businessName : ''}}
                    </el-form-item>
                    <el-form-item label="部门：">
                        {{currentRow?currentRow.departmentName:''}}
                    </el-form-item>
                    <el-form-item label="职级：">
                        {{currentRow?currentRow.rankName:''}}
                    </el-form-item>
                    <el-form-item label="绝对值：">
                        {{currentRow?(currentRow.rankMagnitude+"%"):''}}
                    </el-form-item>
                    <el-form-item label="员工：" prop="staffId">
                        <el-select v-model="ruleForm.staffId" placeholder="请选择">
                            <el-option
                                    v-for="item in currentPersonList"
                                    :key="item.id"
                                    :label="item.staffName + ' ' + item.staffCode"
                                    :value="item.id">
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="绝对值：" prop="absolute">
                        <el-input v-model="ruleForm.absolute" class="w-200"></el-input>
                        %
                    </el-form-item>
                </el-form>
                <span slot="footer" class="dialog-footer">
                    <el-button @click="dialogVisible = false">取 消</el-button>
                    <el-button type="primary" @click="submitForm('ruleForm')">{{handleStaffIndex < 0  ? '确 定' : '修 改'}}</el-button>
                </span>
            </el-dialog>
        </div>
    </div>
</template>

<script>
    import api from '@/api/apiPath'

    export default {
        name: "fourthStep",
        data() {
            let numberFormat = (rule, value, callback) => {
                let reg = /^(0|[1-9]\d*)(\s|$|\.\d{1,2}\b)/g;
                if (!reg.test(value)) {
                    callback(new Error('输入格式不正确，请输入数字，保留小数点后两位!'));
                } else if (+value === 0) {
                    callback(new Error('输入格式不正确，绝对值不能为0!'));
                } else {
                    callback();
                }
            };

            return {
                keyword: '',
                tableData: [],
                totalTableData: [],
                currentRow: {},
                // 弹窗
                dialogVisible: false,
                ruleForm: {
                    absolute: '',
                    staffId: ''
                },
                rules: {
                    staffId: [
                        {required: true, message: '请选择员工', trigger: 'blur'},
                    ],
                    absolute: [
                        {required: true, message: '请输入绝对值', trigger: 'blur'},
                        {validator: numberFormat, trigger: 'blur'}
                    ],
                },
                personSettingMap: {},

                currentPersonList: [],
                rankListMap: {},  // 职级映射表
                tableConfig: {
                    pageNum: 1,
                    pageSize: 10,
                    totalSize: 10
                },
                handleStaffIndex: -1,  // -1为新增， 其他为索引
                handleStaffId: 0,  // -1为新增， 其他为索引
                ruleId: 0,
                projectFixedPersonList: [],
            }
        },
        props: ['fourthUse', 'renderData4'],
        created() {
            this.searchHandle()
        },
        watch: {
            fourthUse: {
                handler(newValue, oldvalue) {
                    this.ruleId = newValue;
                    // 如果更改了规则，则清空定投人员
                    if (newValue !== oldvalue && !this.renderData4.length) {
                        this.personSettingMap = {};
                        this.currentPersonList = [];
                    }
                    this.searchHandle()
                },
                deep: true,
                immediate: true
            },
            renderData4() {
                if (this.renderData4.length) {
                    console.log(this.renderData4.length);
                    this.formatList(this.renderData4);
                }
            }
        },
        methods: {
            formatList(personList) {
                personList.forEach((item) => {
                    if (item.distributionRuleId) {
                        if (this.personSettingMap[item.distributionRuleId]) {
                            this.personSettingMap[item.distributionRuleId].push({
                                "staffId": item.userId,
                                "staffName": item.userName,
                                "staffCode": item.jobNum,
                                "absolute": item.absoluteNum,
                                "distributionRuleId": item.distributionRuleId
                            })
                        } else {
                            this.$set(this.personSettingMap, item.distributionRuleId, [{
                                "staffId": item.userId,
                                "staffName": item.userName,
                                "staffCode": item.jobNum,
                                "absolute": item.absoluteNum,
                                "distributionRuleId": item.distributionRuleId
                            }])


                        }
                    }
                })
                console.log(this.personSettingMap);
            },
            calcTableData() {
                this.tableData = this.totalTableData.slice((this.tableConfig.pageNum - 1) * this.tableConfig.pageSize, this.tableConfig.pageNum * this.tableConfig.pageSize)
            },
            handleStaff(type, index, row) {
                if (type === 'edit') {
                    this.ruleForm = {
                        absolute: row.absolute,
                        staffId: row.staffId
                    };
                    this.handleStaffIndex = index;
                    this.handleStaffId = row.staffId;
                    this.axios.post(api.getStaffByStationIdDialog, {
                        stationId: this.currentRow.rankId
                    }).then((res) => {
                        this.currentPersonList = res.data.data;
                        this.dialogVisible = true
                    });
                } else {
                    this.personSettingMap[this.currentRow.id].splice(index, 1);
                }
            },
            handleSizeChange(size) {
                this.tableConfig.pageNum = 1;
                this.tableConfig.pageSize = size;
                this.calcTableData()
            },
            handleCurrentChange(page) {
                this.tableConfig.pageNum = page;
                this.currentRow = {};
                this.calcTableData()
            },
            filterList() {
                this.tableConfig.pageNum = 1;
                this.searchHandle();
            },
            clickRow(row) {
                this.currentRow = row;
                if (!this.personSettingMap[this.currentRow.id]) {
                    this.personSettingMap[this.currentRow.id] = []
                }
            },

            // 查各职级
            searchHandle() {
                this.axios.post(api.getRuleDetailList, {
                    rankName: this.keyword,
                    ruleId: this.ruleId || 112,
                    pageNum: this.tableConfig.pageNum,
                    pageSize: 0,
                }).then((res) => {
                    if (res.data.code === 200) {
                        this.totalTableData = res.data.data.list;
                        this.tableConfig.totalSize = this.totalTableData.length;
                        this.calcTableData();
                        let rankListMap = {};
                        this.totalTableData.forEach(item => {
                            rankListMap[item.rankId] = item;
                        });
                        this.rankListMap = rankListMap;
                    }
                })
            },
            // 职级下面新增员工
            addChild() {
                if (this.currentRow.id) {
                    this.ruleForm = {
                        absolute: '',
                        staffId: ''
                    };
                    this.handleStaffId = 0;
                    this.handleStaffIndex = -1;
                    this.axios.post(api.getStaffByStationIdDialog, {
                        stationId: this.currentRow.rankId
                    }).then((res) => {
                        this.currentPersonList = res.data.data;
                        this.dialogVisible = true
                    });
                } else {
                    this.$message.warning('请先选择职级')
                }
            },

            calcStaffScaleSumIsOverflow(handleStaffIndex) {
                let max = this.currentRow.rankMagnitude;
                let current = +this.ruleForm.absolute;
                let sum = 0;
                this.personSettingMap[this.currentRow.id].forEach((item, index) => {
                    if (handleStaffIndex !== index) {
                        sum += item.absolute * 1;
                    }
                });
                if (current + sum > max) {
                    this.$message.warning('员工绝对值总和不能大于职级的绝对值！')
                    return true;
                }
                return false;
            },

            submitForm(formName) {
                this.$refs[formName].validate((valid) => {
                    if (valid) {
                        let isHas = this.personSettingMap[this.currentRow.id].find((item) => {
                            return item.staffId === this.ruleForm.staffId
                        });
                        if (isHas && this.ruleForm.staffId !== this.handleStaffId) {
                            this.$message.warning('该员工已经存在！')
                            return false;
                        } else {
                            let findStaff = this.currentPersonList.find(item => {
                                return item.id === this.ruleForm.staffId
                            });
                            //handleStaffIndex  -1说明新增，其他是修改
                            if (this.handleStaffIndex < 0) {
                                // 员工总和绝对值超出职级绝对值
                                if (this.calcStaffScaleSumIsOverflow()) {
                                    return false;
                                }
                                this.personSettingMap[this.currentRow.id].push({
                                    staffId: this.ruleForm.staffId,
                                    staffName: findStaff.staffName,
                                    staffCode: findStaff.staffCode,
                                    absolute: this.ruleForm.absolute,
                                    distributionRuleId: this.currentRow.id
                                });
                            } else {
                                // 员工总和绝对值超出职级绝对值
                                if (this.calcStaffScaleSumIsOverflow(this.handleStaffIndex)) {
                                    return false;
                                }
                                this.$set(this.personSettingMap[this.currentRow.id], this.handleStaffIndex, {
                                    staffId: this.ruleForm.staffId,
                                    staffName: findStaff.staffName,
                                    staffCode: findStaff.staffCode,
                                    absolute: this.ruleForm.absolute,
                                    distributionRuleId: this.currentRow.id
                                })
                            }
                            this.dialogVisible = false;
                        }
                    } else {
                        return false;
                    }
                });
            },
            isCanGoNextStep() {
                let projectFixedPersonList = [];

                for (let i = 0, len = this.totalTableData.length; i < len; i++) {
                    let item = this.totalTableData[i];
                    let currentDataList = this.personSettingMap[item.id] || [];
                    let sum = 0;

                    currentDataList.forEach(item => {
                        sum += item.absolute * 1;
                        projectFixedPersonList.push({
                            absoluteNum: item.absolute,
                            jobNum: item.staffCode,
                            userName: item.staffName,
                            userId: item.staffId,
                            userProportion: item.staffCode,
                            distributionRuleId: item.distributionRuleId,
                            userInvestMoney: item.staffCode,
                            returnMoney: item.returnMoney,
                            rateOfReturn: item.rateOfReturn,
                        })
                    });
                    if (+sum.toFixed(2) !== +item.rankMagnitude.toFixed(2)) {
                        this.$message.warning(`${item.businessName} ${item.departmentName} ${item.rankName} 项有误，职级下员工绝对值总和必须等于职级的绝对值！`);
                        return false;
                    }
                }
                this.projectFixedPersonList = projectFixedPersonList
                return true;
            }
        }
    }

</script>

<style scoped lang="stylus">
    .fourth-content {
        display: flex;
        & > div {
            width: 500px;
            padding: 15px;
        }
        .fourth-left {
            border-right: 1px solid #ccc;
        }
        .search-line {
            margin-bottom: 20px;
        }
    }
</style>
